package com.jt.assistant.ui

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.jt.assistant.R
import com.jt.assistant.viewmodel.HomeViewModel
import com.jt.assistant.viewmodel.LoginViewModel
import com.yzp.mvvmlibrary.base.BaseActivity
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import kotlinx.android.synthetic.main.activity_login.*

/**
 * 登录
 */
class LoginActivity : BaseActivity<LoginViewModel>() {

    override fun layoutId(): Int = R.layout.activity_login

    override fun initView(savedInstanceState: Bundle?) {
    }

    override fun initData() {
        val userName = MMKV.defaultMMKV().getString("USERNAME", "")
        val password = MMKV.defaultMMKV().getString("PASSWORD", "")

        if (!userName.isNullOrEmpty() && !password.isNullOrEmpty()) {
            login_username_edit.setText(userName)
            login_password_edit.setText(password)
            Handler().postDelayed(Runnable {
                viewModel.login(userName, password)
            }, 500)
        }
    }

    override fun initListener() {
        login_submit.setOnClickListener {
            val userName = login_username_edit.text.toString()
            val passWord = login_password_edit.text.toString()
            when {
                userName.isEmpty() -> {
                    ToastUtils.showShort("请输入账户")
                }
                passWord.isEmpty() -> {
                    ToastUtils.showShort("请输入密码")
                }
                else -> {
                    viewModel.login(userName, passWord)
                }
            }
        }
        viewModel.mLogin.observe(this, Observer {
            if (it.isSuccess()) {
                MMKV.defaultMMKV().putString("ROLENAMELIST", GsonUtils.toJson(it.data.roleNameList))
                MMKV.defaultMMKV().putString("NAME", it.data.name)
                MMKV.defaultMMKV().putString("TOKEN", it.data.token)
                MMKV.defaultMMKV().putString("USERNAME", login_username_edit.text.toString())
                MMKV.defaultMMKV().putString("PASSWORD", login_password_edit.text.toString())
                startActivity(Intent(this@LoginActivity, HomeActivity::class.java))
                finish()
            }
        })
    }
}